# 导入相关库和模块
from fastapi import APIRouter, Depends, HTTPException, Query, Request
from sqlalchemy.orm import Session
from database import SessionLocal
import sys
from admin.base_controller import BaseController
from config.logging import logger
from services.admin.sys_admin_api_service import SysAdminApiService
from datetime import datetime

# 定义获取数据库会话的依赖
def get_db():
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()


# 定义控制器类
class SysAdminApi(BaseController):
    def __init__(self):
        super().__init__()
        self.router = APIRouter()

    async def sys_admin_list(self,  searchData: dict = None, db: Session = Depends(get_db), email: str = Query(None), userName: str = Query(None),
                         page: int = Query(default=1, ge=1), limit: int = Query(default=20, ge=1)):
        """
        管理员列表
        :param email:
        :param db:
        :param userName:
        :param page:
        :param limit:
        :param searchData: 查询条件 {"nickName": "admin", "status": "0"}
        :return:
        """
        service = SysAdminApiService(db)
        lists = await service.sys_admin_list(page, limit, email, userName, searchData)
        return self.success_response(data=lists, message="success")

    async def sys_login(self, userData:dict, db: Session = Depends(get_db)):
        """
        用户登录
        :param userData:
        :param db:
        :return:
        """
        service = SysAdminApiService(db)
        result = await service.sys_login(userData)
        return self.success_response(data=result, message="success")

    async def sys_create_user(self, userData: dict , request: Request,  db: Session = Depends(get_db)):
        """
        创建用户
        :param userData:json {userName,postId,phoneNumber,email,dept,nickName,password,sex,status,roleId,remark}
        :param db:
        :param request:
        :return:

        """
        service = SysAdminApiService(db)
        # 补齐数据
        userData['userType'] = "00" if "userType" not in userData else userData['userType']
        userData['status'] = 0 if "status" not in userData else userData['status']
        userData['loginIp'] = request.client.host
        userData['loginDate'] = datetime.now()
        result = await service.sys_create_user(userData)
        if isinstance(result, dict) and "error" in result:
            return self.failure_response(status_code=400, message=result["error"])
        return self.success_response(data=result, message="success")

    async def sys_update_user(self, userData: dict, userId:int,request: Request, db: Session = Depends(get_db)):
        """
        更新用户
        :param userId: 用户ID
        :param userData: json {user: {...}, role: {...}, post: {...}}
        :param db: Session instance
        :param request: Request instance
        :return: JSON response
        """
        service = SysAdminApiService(db)

        result = await service.sys_update_user(userData, userId)
        if isinstance(result, dict) and "error" in result:
            return self.failure_response(status_code=400, message=result["error"])
        return self.success_response(data=result, message="success")

    async def sys_detail_user(self,userId: int, db: Session = Depends(get_db)):
        """
        获取用户详细信息
        :param userId: 用户ID
        :param db: Session instance
        :return: JSON response
        """
        service = SysAdminApiService(db)

        result = await service.sys_detail_user(userId)
        if isinstance(result, dict) and "error" in result:
            return self.failure_response(status_code=400, message=result["error"])
        return self.success_response(data=result, message="success")

    async def sys_delete_user(self, userId: int, db: Session = Depends(get_db)):
        """
        删除用户
        :param userId: 用户ID
        :param db: Session instance
        :return: JSON response
        """
        service = SysAdminApiService(db)

        result = await service.sys_delete_user(userId)
        if isinstance(result, dict) and "error" in result:
            return self.failure_response(status_code=400, message=result["error"])
        return self.success_response(data=result, message="success")

    async def sys_user_info(self, request:Request, db: Session = Depends(get_db)):
        """
        获取当前登录用户信息
        :param db: Session instance
        :return: JSON response
        """
        service = SysAdminApiService(db)
        result = await service.sys_user_info(request.state.user['id'])
        return self.success_response(data=result, message="success")
# 使用
sys_admin_api = SysAdminApi()
router = sys_admin_api.router
